/**
 * FormPrinc.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormPrinc.java
 * Created on 15/03/2009, 22:24:40
 */
package trabpoo;

import java.sql.PreparedStatement;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import plagio.postgres.ConnectionPostgres;
import plagio.utils.Treatments;
import plagio.utils.TreatmentStemmer;
import java.util.Vector;
import java.util.Date;
import java.util.Properties;

/**
 *
 * @author jmsandy
 */
public class FormPrinc extends javax.swing.JFrame {
    private String[] languages = {"Portuguese", "English"};
    private JComboBox cLanguages = new JComboBox(languages);
    
    public FormPrinc() {
        initComponents();
        // Setting up all the columns of the table to not allow them to resize.
        tableShow.getColumnModel().getColumn(0).setPreferredWidth(50);
        tableShow.getColumnModel().getColumn(0).setResizable(false);
        tableShow.getColumnModel().getColumn(1).setPreferredWidth(120);
        tableShow.getColumnModel().getColumn(1).setResizable(false);
        tableShow.getColumnModel().getColumn(2).setPreferredWidth(280);
        tableShow.getColumnModel().getColumn(2).setResizable(false);
        tableShow.getColumnModel().getColumn(3).setPreferredWidth(482);
        tableShow.getColumnModel().getColumn(3).setResizable(false);
        // Adding a combobox to se  lect the language.
        tableShow.getColumn(tableShow.getColumnName(1)).setCellEditor(
                new DefaultCellEditor(this.cLanguages));
        tableShow.getTableHeader().setReorderingAllowed(false);
        tableShow.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fileChooser.setAcceptAllFileFilterUsed(false);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        fileChooser = new javax.swing.JFileChooser();
        jSeparator1 = new javax.swing.JSeparator();
        openFile = new javax.swing.JToggleButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableShow = new javax.swing.JTable();
        importFile = new javax.swing.JToggleButton();
        lbTotalFile = new javax.swing.JLabel();
        progressTotal = new javax.swing.JProgressBar();
        btnClose = new javax.swing.JToggleButton();
        compareFile = new javax.swing.JToggleButton();
        about = new javax.swing.JToggleButton();
        clearFile = new javax.swing.JToggleButton();

        fileChooser.setApproveButtonText("Open");
        fileChooser.setApproveButtonToolTipText("Open files Selected");
        fileChooser.setMultiSelectionEnabled(true);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Programming Natural Language");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        openFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/trabpoo/images/searchFile.png"))); // NOI18N
        openFile.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, openFile, org.jdesktop.beansbinding.ELProperty.create("Open File"), openFile, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"));
        bindingGroup.addBinding(binding);

        openFile.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                openFileMouseClicked(evt);
            }
        });

        tableShow.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Import", "Language", "Author", "Text"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                true, true, true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableShow.setRowHeight(30);
        jScrollPane1.setViewportView(tableShow);

        importFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/trabpoo/images/importFile.png"))); // NOI18N
        importFile.setToolTipText("Import File");
        importFile.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        importFile.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                importFileMouseClicked(evt);
            }
        });
        importFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importFileActionPerformed(evt);
            }
        });

        lbTotalFile.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
        lbTotalFile.setText("Status ");

        progressTotal.setStringPainted(true);

        btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/trabpoo/images/exit.png"))); // NOI18N
        btnClose.setToolTipText("Close");
        btnClose.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        btnClose.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCloseMouseClicked(evt);
            }
        });

        compareFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/trabpoo/images/compareFile.png"))); // NOI18N
        compareFile.setToolTipText("Compare file");
        compareFile.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        compareFile.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                compareFileMouseClicked(evt);
            }
        });

        about.setIcon(new javax.swing.ImageIcon(getClass().getResource("/trabpoo/images/about.png"))); // NOI18N
        about.setToolTipText("About");
        about.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        about.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                aboutMouseClicked(evt);
            }
        });

        clearFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/trabpoo/images/clear.png"))); // NOI18N
        clearFile.setToolTipText("Clear Fields");
        clearFile.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        clearFile.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                clearFileMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(openFile, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(35, 35, 35)
                        .addComponent(importFile, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(33, 33, 33)
                        .addComponent(compareFile, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31)
                        .addComponent(clearFile, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 441, Short.MAX_VALUE)
                        .addComponent(about, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbTotalFile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(progressTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 869, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 936, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(importFile, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(openFile, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(compareFile, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(about, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(clearFile, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbTotalFile)
                    .addComponent(progressTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        bindingGroup.bind();

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-970)/2, (screenSize.height-494)/2, 970, 494);
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("static-access")
    private void openFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openFileMouseClicked
        // TODO add your handling code here:
        fileChooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File file) {
                String name = file.getName().toLowerCase();
                return name.endsWith(".txt") || file.isDirectory();
            }
            @Override
            public String getDescription() {
                return ".txt";
            }
        });

        int state = fileChooser.showOpenDialog(null);
        if(state == JFileChooser.APPROVE_OPTION){
            showResult();
        }
    }//GEN-LAST:event_openFileMouseClicked

    private void importFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_importFileMouseClicked
        // Take list with elements selected.
        if(JOptionPane.showConfirmDialog(this, "Confirms the import?",
              "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){            
            // Checking if the list have elements selected.
            ArrayList list = selectionList();
            if(!list.isEmpty()){

                Treatments treatFiles = new Treatments(list);
                if(treatFiles.convFilesBin()){
                    insertBD(treatFiles.getListStream(), list);
                }else{
                    JOptionPane.showMessageDialog(this, "Failed conversion!");
                }
            }else{ // Error Message
                JOptionPane.showMessageDialog(this, "No record selected.");
            }
        }
}//GEN-LAST:event_importFileMouseClicked

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_formWindowClosed

    private void btnCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCloseMouseClicked
            // TODO add your handling code here:
        System.exit(0);
}//GEN-LAST:event_btnCloseMouseClicked

    private void importFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importFileActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_importFileActionPerformed

    private void aboutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_aboutMouseClicked
        // TODO add your handling code here:
        FormAbout fmAbout = new FormAbout();
        fmAbout.setModal(true);
        fmAbout.setVisible(true);
    }//GEN-LAST:event_aboutMouseClicked

    private void compareFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_compareFileMouseClicked
        // TODO add your handling code here:
        FormCompar fmCompar = new FormCompar();
        fmCompar.setModal(true);
        fmCompar.setVisible(true);
    }//GEN-LAST:event_compareFileMouseClicked

    private void clearFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearFileMouseClicked
        // TODO add your handling code here:
        // Clear all fields.
        progressTotal.setValue(0);
        progressTotal.updateUI();
        DefaultTableModel def = (DefaultTableModel)tableShow.getModel();
        def.getDataVector().clear();
        tableShow.updateUI();
    }//GEN-LAST:event_clearFileMouseClicked
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FormPrinc form = new FormPrinc();
                form.setIconImage(new ImageIcon("icone.png").getImage());
                form.setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton about;
    private javax.swing.JToggleButton btnClose;
    private javax.swing.JToggleButton clearFile;
    private javax.swing.JToggleButton compareFile;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JToggleButton importFile;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lbTotalFile;
    private javax.swing.JToggleButton openFile;
    private javax.swing.JProgressBar progressTotal;
    private javax.swing.JTable tableShow;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private void showResult(){
        File[] records = fileChooser.getSelectedFiles();
        DefaultTableModel def = (DefaultTableModel)tableShow.getModel();
        def.getDataVector().clear();
        tableShow.updateUI();
        for(int i = 0; i < records.length; i++){
            Object[] row = new Object[]{false, "Portuguese", "",
            records[i].getAbsolutePath()};
            def.addRow(row);
        }
    }

    private ArrayList selectionList(){
        ArrayList list = new ArrayList();
        DefaultTableModel def = (DefaultTableModel)tableShow.getModel();
        for(int i = 0; i < tableShow.getRowCount(); i++){
            Object select = (Boolean)tableShow.getValueAt(i, 0);
            if(Boolean.parseBoolean(select.toString())){
                list.add(def.getDataVector().elementAt(i));
            }
        }
        return list;
    }

    private void insertBD(Vector lstFiles, ArrayList list){
        int inserted = 0, nInserted = 0;
        Thread totalThread = new Thread();
        totalThread.start();
        int progress = (int)(100 / lstFiles.size());
        for(int i = 0; i < lstFiles.size(); i++){
            byte[] file = (byte[])lstFiles.get(i);
            Vector vet = (Vector)list.get(i);

            // Checks the situation of a insertion.
            if(insertFile(file, vet) )  inserted++;
            else nInserted++;

            progressTotal.setValue(++progress);
            progressTotal.getUI().update(progressTotal.getGraphics(),
            progressTotal);
            try{ Thread.sleep(10);}
            catch(InterruptedException e){}
        }
        if(progressTotal.getValue() < 100) progressTotal.setValue(100);

        DefaultTableModel def = (DefaultTableModel)tableShow.getModel();
        def.getDataVector().clear();
        tableShow.updateUI();

        String res = "";
        if(inserted <= 1) res = inserted + " record inserted.";
        else res = inserted + " records inserted.";

        if(nInserted > 0){
            if(nInserted == 1) res += "\n" + nInserted + " record not insered.";
            else res += "\n" + nInserted + " records not insered.";
        }

        JOptionPane.showMessageDialog(this, res);
    }    

    private boolean insertFile(byte[] file, Vector vet){
        boolean ok = true;
        try{
            File fileName = new File(vet.elementAt(3).toString());
            TreatmentStemmer stem = new TreatmentStemmer();
            Date date = new Date();

            // Broken the text in words
            if(getPositionBox(vet.elementAt(1).toString()) != 2){
                StringBuilder builder = stem.breakText(fileName,
                                  getPositionBox(vet.elementAt(1).toString()));

                // Creates connection with database
                Properties props = System.getProperties();
                props.load(ClassLoader.getSystemResourceAsStream("plagio.properties"));
                ConnectionPostgres conn = new ConnectionPostgres();
                if(conn.connection(props.getProperty("user"),
                    props.getProperty("password"),props.getProperty("url"))){
                    // Inserting the file imported.
                    PreparedStatement stat;
                    String query = "insert into \"FileImport\"(title, author, extension";
                    query += ",idiom, dateimport, file, stemmerFile) VALUES ";
                    query += "(?,?,?,?,?,?,?)";
                    stat = conn.getConnection().prepareStatement(query);
                    stat.setString(1, fileName.getName().toUpperCase());
                    stat.setString(2, vet.elementAt(2).toString().toUpperCase());
                    stat.setString(3, "txt".toUpperCase());
                    stat.setInt(4, getPositionBox(vet.elementAt(1).toString()));
                    stat.setDate(5, new java.sql.Date(date.getTime()));
                    stat.setBytes(6, file);
                    stat.setString(7, builder.toString().toUpperCase());
                    stat.executeUpdate();
                    stat.close();
                    conn.closeConnection();
                }
            }
            else ok = false;
        }catch(Exception e){
            ok = false;
            System.out.print(e.getMessage() + " ");
        }
        return ok;
    }

    private int getPositionBox(String s){
        int position = 0;
        if(s.equals("Portuguese")) position = 1;
        else if(s.equals("English")) position = 2;
        return position;
    }
}